//
//  xsConfigurationMusicCollectionView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/8/30.
//

#import "xsConfigurationMusicCollectionView.h"
  
@interface xsConfigurationMusicCollectionView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)NSInteger audioType;// 0我的 1官方

@property (nonatomic,strong) UIView *tableEmptyView;
@property (nonatomic,weak) UIImageView * tableEmptyImage;
@property (nonatomic,weak) UILabel * tableEmptyLabel;
@property (nonatomic,weak) UIButton *covertableEmptyViewButton;

@property (nonatomic,assign)NSInteger page;

@end

@implementation xsConfigurationMusicCollectionView

- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout  withAudioType:(NSInteger)audioType{
    
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if(self){
        self.delegate = self;
        self.dataSource = self;
        self.page = 1;
        self.backgroundColor = UIColor.clearColor;//COLOR_VCViewBgcolor;
        self.audioType = audioType;
        //        //注册cell
        [self registerClass:[xsConfigurationMusicCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([xsConfigurationMusicCollectionViewCell class])];
        [self registerClass:[xsConfigurationMusicCollectionViewHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([xsConfigurationMusicCollectionViewHeadView class])];
        
        [self addSubview:self.tableEmptyView];
        [self.tableEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(250, 250));
        }];
        
        XSWeakSelf;
        self.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf.dataArray removeAllObjects];
            [weakSelf getAudioDataWithAspectRatio:audioType];
        }];
        [self.mj_header beginRefreshing];
    }
    
    return self;
}

#pragma mark - UICollectionViewDataSource
//一共有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//每一组有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    self.tableEmptyView.hidden = self.dataArray.count;
    return self.dataArray.count;
}

//每一个cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    xsConfigurationMusicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([xsConfigurationMusicCollectionViewCell class]) forIndexPath:indexPath];
    
    if (indexPath.row<self.dataArray.count) {
        cell.model = self.dataArray[indexPath.item];
    }
    cell.backgroundColor = UIColor.grayColor;
    cell.contentView.backgroundColor = UIColor.clearColor;
    cell.layer.cornerRadius = 6.0;
    cell.layer.masksToBounds = YES;
    
    return cell;
}

//和tableView差不多, 可设置头部和尾部
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        xsConfigurationMusicCollectionViewHeadView *headerView = [self dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([xsConfigurationMusicCollectionViewHeadView class]) forIndexPath:indexPath];
        headerView.backgroundColor = UIColor.clearColor;
        return headerView;
    }
    return nil;
}

//每一个分组的上左下右间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0);
}

//头部视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(self.frame.size.width, 45.0);
    return CGSizeMake(self.frame.size.width, 0.10);
}


//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat margin = 5.0*6.0;
    CGFloat itemW =  floor((self.frame.size.width-margin)*0.2);
    CGFloat itemH = itemW;
    return CGSizeMake(itemW, itemH);
}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.item<self.dataArray.count){
        xsConfigurationMusicCollectionViewCellModel *model = self.dataArray[indexPath.item];
        NSLog(@"model.name==%@\n",model.name);
        for (xsConfigurationMusicCollectionViewCellModel *tempModel in self.dataArray) {
            if(tempModel.Id != model.Id){
                tempModel.isBeClick = NO;
            }
        }
        model.isBeClick = YES;
        
        XSLogMethod
        if([self.delegateConfigurationMusic respondsToSelector:@selector(xsConfigurationMusicCollectionCellBeClick: withAudioType:)]){
            [self.delegateConfigurationMusic xsConfigurationMusicCollectionCellBeClick:model withAudioType:self.audioType];
        }
        [self reloadData];
    }
}

//
////在开始移动是调动此代理方法
//- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"开始移动");
//    return YES;
//}

////在移动结束的时候调用此代理方法
//- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
//    NSLog(@"结束移动");
//
//}

////audioType;// 0我的 1官方
- (void)getAudioDataWithAspectRatio:(NSInteger)audioType
{
//
    
    XSWeakSelf;

    
//    NSString *tempUrl = @"https://mall219.writemall.com/bossapi/digitalHuman/voiceList";
    NSString *tempUrl = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"digitalHuman/voiceList"];
     if(audioType!=0){
//        tempUrl = @"https://mall219.writemall.com/bossapi/speech/voiceTemplateList";
         tempUrl = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"speech/voiceTemplateList"];
    }
   
    
    NSDictionary *pramerDict = @{};
    [[ZYFDataManager sharedInstance] GET:tempUrl dict:pramerDict succeed:^(id data) {
        
        
        // audioType;// 0我的 1官方
        if(audioType==0){
            NSLog(@"我的配音tempUrl==%@--data==%@\n",tempUrl,data);
        }
        else{
            NSLog(@"官方配音--tempUrl==%@--data==%@\n",tempUrl,data);
        }
        NSDictionary *dictData = data;
        if([dictData isKindOfClass:[NSDictionary class]]){
            if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
                NSInteger codeInt = [dictData[@"code"] integerValue];
                if(codeInt==200){
                    
                    if([dictData[@"data"] isKindOfClass:[NSArray class]]){
                        NSArray *dataArr3  = dictData[@"data"];
                        
                        if(dataArr3.count>0){
                            for (int ii=0; ii<dataArr3.count; ii++) {
                                NSDictionary *tempFinalDict = dataArr3[ii];
                                xsConfigurationMusicCollectionViewCellModel *md = [xsConfigurationMusicCollectionViewCellModel yy_modelWithDictionary:tempFinalDict];
                                //md.url = tempFinalDict[@"url"];
                                if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
                                   [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
                                   NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
                                    md.Id = [tempIdStr integerValue];
                                }
                                if([tempFinalDict[@"description"] isKindOfClass:[NSString class]]){
                                   NSString *tempDescriptionStr = tempFinalDict[@"description"];
                                    md.Description = tempDescriptionStr;
                                }
                                md.audioType = weakSelf.audioType;
                                
                                [weakSelf.dataArray addObject:md];
                            }
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:weakSelf.dataArray ];
                            });
                        }
                        else{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:nil];
                            });
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf stopEndRefresh:nil];
                        });
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf stopEndRefresh:nil];
                    });
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf stopEndRefresh:nil];
                });
            }
        }
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf stopEndRefresh:nil];
            });
        }
        
    } failure:^(NSDictionary *error) {
        NSLog(@"getAudioDataWithAspectRatio--error.description==%@\n",error.description);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf stopEndRefresh:nil];
        });
    }];
//    [[ZYFDataManager sharedInstance] POST:@"https://mall219.writemall.com/bossapi/speech/voiceTemplateList" dict:pramerDict succeed:^(id data) {} failure:^(NSDictionary *error) {}];
}


- (UIView *)tableEmptyView{
    
    if (!_tableEmptyView) {
        _tableEmptyView = [[UIView alloc] init];
        _tableEmptyView.backgroundColor = UIColor.clearColor;
        
        UITapGestureRecognizer *tableEmptyViewRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [_tableEmptyView addGestureRecognizer:tableEmptyViewRecognizer];
        
        UIImageView *tableEmptyImage = [[UIImageView alloc] init];
        tableEmptyImage.image = [UIImage imageNamed:@"CYNotSearchResultData"];
        [_tableEmptyView addSubview:tableEmptyImage];
        tableEmptyImage.backgroundColor = UIColor.clearColor;
        self.tableEmptyImage = tableEmptyImage;
        
        UILabel *tableEmptyLabel = [[UILabel alloc] init];
        tableEmptyLabel.text = @"暂无数据";//kLocalizedString(@"暂无数据");
        tableEmptyLabel.font = [UIFont systemFontOfSize:16];//Font(16);
        tableEmptyLabel.numberOfLines = 0;
        tableEmptyLabel.textAlignment = NSTextAlignmentCenter;
        tableEmptyLabel.textColor = COLOR_HEX(0x999999);
        [_tableEmptyView addSubview:tableEmptyLabel];
        self.tableEmptyLabel = tableEmptyLabel;
        
        tableEmptyImage.userInteractionEnabled = YES;
        tableEmptyLabel.userInteractionEnabled = YES;

        UITapGestureRecognizer *tableEmptyImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [tableEmptyImage addGestureRecognizer:tableEmptyImageRecognizer];

        UITapGestureRecognizer *tableEmptyLabelRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyLabelGestureEvent:)];
        [tableEmptyLabel addGestureRecognizer:tableEmptyLabelRecognizer];
        
        [tableEmptyImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.top.mas_equalTo(self.tableEmptyView.mas_top).offset(32);
//            make.centerY.equalTo(_tableEmptyView.mas_centerY).offset(-10);
            make.size.mas_equalTo(CGSizeMake(80.55, 86.58));
        }];
        
        [tableEmptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(tableEmptyImage);
            make.top.equalTo(tableEmptyImage.mas_bottom).offset(5);
        }];
        //
        //        UIButton *covertableEmptyViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        covertableEmptyViewButton.backgroundColor = UIColor.purpleColor;//UIColor.clearColor;
        //        [_tableEmptyView addSubview:covertableEmptyViewButton];
        //        self.covertableEmptyViewButton = covertableEmptyViewButton;
        //        XSWeakSelf;
        //        [covertableEmptyViewButton addTapRunWithBlock:^(UIButton * _Nonnull YSBtn) {
        //            if(weakSelf.tableViewNotContentDataBgViewBeClickEvent){
        //                weakSelf.tableViewNotContentDataBgViewBeClickEvent();
        //            }
        //        }];
        
    }
    return _tableEmptyView;
    
}
- (void)tableEmptyImageGestureEvent:(UITapGestureRecognizer *)sender{
    
    [self tableEmptyLabelGestureEvent:sender];
}
- (void)tableEmptyLabelGestureEvent:(UITapGestureRecognizer *)sender{
    
    NSLog(@"tableEmptyLabelGestureEvent");
    
    if(self.dataArray.count<=0){
        //[self getAudioDataWithAspectRatio:self.audioType];
        
        [self.mj_header beginRefreshing];
    }
}


#pragma mark - stopEndRefresh
- (void)stopEndRefresh:(NSArray *) array {
    

    if (self.page  == 1) {
        if (self.mj_footer.isRefreshing) {
            [self.mj_footer endRefreshing];
        }
        [self.mj_header endRefreshing];
        [self.mj_footer resetNoMoreData];
    }else {
        if (array.count > 1) {
            [self.mj_footer endRefreshing];
        }else {
            [self.mj_footer endRefreshingWithNoMoreData];
        }
    }
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself reloadData];
    });
}

// 改变全部的cell为选中或者未选中状态 YES选中  NO未选中
- (void)xsConfigurationMusicCollectionChangAllCellClickState:(BOOL)clickStatu{
    
    
    for (xsConfigurationMusicCollectionViewCellModel *model in self.dataArray) {
        model.isBeClick = clickStatu;
    }
    
    [self reloadData];
}

@end

